'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Typography,
  useTheme,
  CircularProgress,
  FormControl,
  InputLabel,
  Select,
  MenuItem
} from '@mui/material';
import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';

export default function CreateProjectDialog({ open, onClose }) {
  const { t } = useTranslation();
  const theme = useTheme();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [projects, setProjects] = useState([]);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    reuseConfigFrom: ''
  });
  const [error, setError] = useState(null);

  // 获取项目列表
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const response = await fetch('/api/projects');
        if (response.ok) {
          const data = await response.json();
          setProjects(data);
        }
      } catch (error) {
        console.error('获取项目列表失败:', error);
      }
    };

    fetchProjects();
  }, []);

  const handleChange = e => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async e => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/projects', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      if (!response.ok) {
        throw new Error(t('projects.createFailed'));
      }

      const data = await response.json();

      router.push(`/projects/${data.id}/settings?tab=model`);
    } catch (err) {
      console.error(t('projects.createError'), err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 0,
          background: theme.palette.mode === 'dark' ? 'rgba(30, 30, 30, 0.98)' : '#fff',
          boxShadow: 'none',
          border: '1px solid #e0e0e0',
          minWidth: 500
        }
      }}
    >
      <DialogTitle sx={{
        textAlign: 'left',
        fontWeight: 600,
        fontSize: '18px',
        px: 3,
        py: 2,
        pb: 1.5
      }}>
        创建新项目
      </DialogTitle>
      <form onSubmit={handleSubmit}>
        <DialogContent sx={{ px: 3, pt: 1.5, pb: 0 }}>
          <Box sx={{ mb: 2, borderRadius: '6px', mt: '10px', ml: '10px', mr: '10px', background: '#fff' }}>
            {/* 项目名称标签 */}
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.5 }}>
              <Box component="span" sx={{ color: 'rgba(255, 89, 89, 1)', fontSize: '18px', mr: 0.5 }}>*</Box>
              <Box component="span" sx={{ fontSize: '13px', color: '#888', fontWeight: 500 }}>项目名称</Box>
            </Box>
            <TextField
              name="name"
              fullWidth
              required
              value={formData.name}
              onChange={handleChange}
              sx={{ mb: 2, 
                '& .MuiOutlinedInput-root': {
                  borderRadius: 0,
                  fontSize: '14px',
                  height: 40,
                  background: '#fff',
                  '& fieldset': {
                    borderColor: '#e0e0e0'
                  },
                  '&:hover fieldset': {
                    borderColor: '#bdbdbd'
                  },
                  '&.Mui-focused fieldset': {
                    borderColor: '#1976d2'
                  }
                },
                '& .MuiInputLabel-root': {
                  fontSize: '13px',
                  color: '#888'
                }
              }}
              InputLabelProps={{ shrink: true }}
              placeholder="请输入项目名称"
            />
            {/* 描述标签 */}
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.5, mt: 2 }}>
              <Box component="span" sx={{ color: 'rgba(255, 89, 89, 1)', fontSize: '18px', mr: 0.5 }}>*</Box>
              <Box component="span" sx={{ fontSize: '13px', color: '#888', fontWeight: 500 }}>描述</Box>
            </Box>
            <TextField
              name="description"
              fullWidth
              multiline
              rows={4}
              value={formData.description}
              onChange={handleChange}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: 0,
                  fontSize: '14px',
                  background: '#fff',
                  '& fieldset': {
                    borderColor: '#e0e0e0'
                  },
                  '&:hover fieldset': {
                    borderColor: '#bdbdbd'
                  },
                  '&.Mui-focused fieldset': {
                    borderColor: '#1976d2'
                  }
                },
                '& .MuiInputLabel-root': {
                  fontSize: '13px',
                  color: '#888'
                }
              }}
              InputLabelProps={{ shrink: true }}
              placeholder="请输入描述"
            />
            {/* 复用模型配置标签 */}
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.5, mt: 2 }}>
              <Box component="span" sx={{ fontSize: '13px', color: '#888', fontWeight: 500 }}>复用模型配置</Box>
            </Box>
            <FormControl fullWidth>
              <Select
                labelId="reuse-config-label"
                name="reuseConfigFrom"
                value={formData.reuseConfigFrom}
                onChange={handleChange}
                displayEmpty
                sx={{
                  borderRadius: 0,
                  fontSize: '14px',
                  background: '#fff',
                  '& .MuiOutlinedInput-notchedOutline': {
                    borderColor: '#e0e0e0'
                  }
                }}
                inputProps={{ 'aria-label': 'Without label' }}
              >
                <MenuItem value="">不复用</MenuItem>
                {projects.map(project => (
                  <MenuItem key={project.id} value={project.id}>
                    {project.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>
          {error && (
            <Typography color="error" variant="body2" sx={{ mb: 2 }}>
              {error}
            </Typography>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2, pt: 1, justifyContent: 'flex-end', gap: 1 }}>
          <Button
            onClick={onClose}
            variant="contained"
            sx={{
              background: '#f5f5f5',
              borderRadius: 0,
              color: '#666',
              boxShadow: 'none',
              minWidth: 72,
              height: 32,
              fontSize: '14px',
              p: 0,
              '&:hover': {
                background: '#e0e0e0',
                boxShadow: 'none'
              }
            }}
          >
            取消
          </Button>
          <Button
            type="submit"
            variant="contained"
            // 不再禁用按钮，始终可用
            sx={{
              background: 'rgba(35, 127, 250, 1)',
              borderRadius: 0,
              color: 'white',
              boxShadow: 'none',
              minWidth: 90,
              height: 32,
              fontSize: '14px',
              p: 0,
              '&:hover': {
                background: 'rgba(35, 127, 250, 0.85)',
                boxShadow: 'none'
              },
              '&.Mui-disabled': {
                background: 'rgba(35, 127, 250, 0.5)',
                color: 'white',
                opacity: 1
              }
            }}
          >
            {loading ? <CircularProgress size={20} /> : '创建项目'}
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
}
